package com.xiaode.controller.app.task.example;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.Admin;
import com.xiaode.common.model.ExampleActivityTask;
import com.xiaode.common.model.KeyResultsTask;
import com.xiaode.common.model.StudentExampleTask;
import com.xiaode.common.model.StudentTrajectory;
import com.xiaode.common.model.TaskLog;
import com.xiaode.common.model.dto.task.KeyResultsDTO;
import com.xiaode.exce.EnumError;
import com.xiaode.util.UserUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ExampleService {

	/**
     * 发表我的重要他人任务完成情况
     */
    @Before(Tx.class)
    public Ret commitExampleActivity(Integer accountId, Integer userId, Integer taskAlignmentId, String content, String keyResults, String files) throws Exception {

        //创建我的重要他人任务完成情况
        ExampleActivityTask exampleActivity = new ExampleActivityTask();
        exampleActivity.setContent(content);
        exampleActivity.setState(Const.taskState.UNAUDITED);
        exampleActivity.setFiles(files);
        exampleActivity.setUserAccountId(accountId);
        if (taskAlignmentId != null) {
            //  处理任务对齐  查询任务对齐的内容 赋值
            StudentExampleTask exampleTask = StudentExampleTask.dao.findById(taskAlignmentId);
            if (BeanUtil.isEmpty(exampleTask)) {
                return Ret.fail().set("error", EnumError.TASK_NOT_EXIST.getObj());
            }
            if (!exampleTask.getStudentId().equals(userId)) {
                return Ret.fail().set("error", EnumError.TASK_NOT_EXIST.getObj());
            }
            exampleActivity.setTaskAlignment(exampleTask.getContent());
        }
        exampleActivity.save();
        
        //任务记录
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskType(Const.taskType.EXAMPLE_ACTIVITY_TASK_TYPE);
        taskLog.setTaskState(Const.taskState.UNAUDITED);
        taskLog.setTaskDate(LocalDateTime.now());
        taskLog.setUserAccountId(accountId);
        taskLog.setTaskId(exampleActivity.getId());
        taskLog.save();
        
        //处理关键结果
        List<KeyResultsDTO> keyResultsDTOS = JSONUtil.toList(keyResults, KeyResultsDTO.class);
        ArrayList<KeyResultsTask> results = new ArrayList<>(keyResultsDTOS.size());
        //校验关键结果长度是否超过限制
        for (KeyResultsDTO keyResultsDTO : keyResultsDTOS) {
            String dtoContent = keyResultsDTO.getContent();
            if (dtoContent.length() > 200) {
                return Ret.fail().set("error", EnumError.KEY_RES_LENGTH_TOO_LONG.getObj());
            }
            if(dtoContent.length() > 0) {
            	KeyResultsTask res = new KeyResultsTask();
                res.setContent(dtoContent);
                res.setFiles(keyResultsDTO.getFiles());
                res.setTaskType(Const.taskType.EXAMPLE_ACTIVITY_TASK_TYPE);
                res.setTaskId(exampleActivity.getId());
                results.add(res);
            }
        }
        Db.batchSave(results, results.size());
        
        return Ret.ok();
    }

    /**
     * 查询我的重要他人任务列表
     */
    public Ret findExampleActivetyPage(Integer accountId, Integer accountIdMy, Integer page, Integer limit) throws Exception {
        Page<ExampleActivityTask> exampleTaskPage = new Page<ExampleActivityTask>();
        if(accountId != null) {
            exampleTaskPage = ExampleActivityTask.dao.paginate(page, limit, "SELECT *", "FROM example_activity_task WHERE user_account_id = ? AND evaluate_account_id IS NOT NULL ORDER BY id DESC", accountId);
        }else {
            exampleTaskPage = ExampleActivityTask.dao.paginate(page, limit, "SELECT *", "FROM example_activity_task WHERE user_account_id = ? ORDER BY id DESC", accountIdMy);
        }
        for(ExampleActivityTask exampleActivityTask : exampleTaskPage.getList()) {
        	List<KeyResultsTask> keyResultsTaskList = KeyResultsTask.dao.find("SELECT * FROM key_results_task WHERE task_id = ? AND task_type = ?", exampleActivityTask.getId(), Const.taskType.EXAMPLE_ACTIVITY_TASK_TYPE);
        	exampleActivityTask.put("keyResultsTaskList", keyResultsTaskList);
        	
        	//添加审核老师信息
            if (exampleActivityTask.getInt("evaluate_account_id") != null) {
                Integer teaAccountId = exampleActivityTask.getInt("evaluate_account_id");
                Record o = Redis.use().hget(Const.user.AccountIdInfo, teaAccountId);
                Admin admin = Redis.use().get(Const.user.Admin + o.getInt("id"));
                exampleActivityTask.put("teaName", admin.getName());
                exampleActivityTask.put("teaId", admin.getId());
                exampleActivityTask.put("teaAccountId", admin.getAccountId());
                exampleActivityTask.put("teaGender", admin.getGender());
                exampleActivityTask.put("teaPic", admin.getAvatarUrl());
            }
        }
        return Ret.ok().set("exampleActivetyPage", exampleTaskPage);
    }
    
    /**
     * 任务审核
     */
    public Ret examine(Integer accountId, Integer userType, Integer taskId, Integer score, String content, Boolean addTrajectory) throws Exception {
    	//如果当前用户不是教师
        if (userType != Const.UserType.admin) {
            return Ret.fail().set("error", EnumError.ALLOW_ADMIN_EXAMINE.getObj());
        }
    	ExampleActivityTask activityTask = ExampleActivityTask.dao.findById(taskId);
        if (BeanUtil.isEmpty(activityTask)) {
            return Ret.fail().set("error", EnumError.TASK_NOT_EXIST.getObj());
        }
        if (activityTask.getState().intValue() == Const.taskState.REVIEWED) {
            return Ret.fail().set("error", EnumError.TASK_HAVA_EXAMINED.getObj());
        }
        //更新任务审核信息
        activityTask.setScoreTeacher(score);
        activityTask.setEvaluateTime(LocalDateTime.now());
        activityTask.setEvaluateContent(content);
        activityTask.setEvaluateAccountId(accountId);
        activityTask.setState(Const.taskState.REVIEWED);
        activityTask.setUpdateTime(LocalDateTime.now());
        activityTask.update();
        //跟新任务记录
        TaskLog taskLog = TaskLog.dao.findFirst("SELECT * FROM task_log WHERE task_id = ? AND task_type = ?", taskId, Const.taskType.EXAMPLE_ACTIVITY_TASK_TYPE);
        taskLog.setTaskId(taskId);
        taskLog.setEvaluateAccountId(accountId);
        taskLog.setEvaluateTime(LocalDateTime.now());
        taskLog.setTaskState(Const.taskState.REVIEWED);
        taskLog.setUpdateTime(LocalDateTime.now());
        taskLog.update();
        //加入轨迹图
        if (score >= 3 && addTrajectory){
        	StudentTrajectory studentTrajectory = new StudentTrajectory();
            studentTrajectory.setTaskId(taskId);
            studentTrajectory.setTaskType(Const.taskType.EXAMPLE_ACTIVITY_TASK_TYPE);
            studentTrajectory.setUserAccountId(activityTask.getUserAccountId());
            studentTrajectory.setContent(activityTask.getContent());
            studentTrajectory.save();
        }
        //给学生加分
        if (score > 0) {
            Record record = Redis.use().hget(Const.user.AccountIdInfo, activityTask.getUserAccountId());
            UserUtil.addScoreForStu(record.getInt("id"), score, Const.addMarkEventType.EXAMPLE_TASK, activityTask.getId());
        }
        
        return Ret.ok();
    }
    

}
